package com.example.tutorial.mytodolist;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.tutorial.model.DaoMaster;
import com.example.tutorial.model.DaoMaster.DevOpenHelper;
import com.example.tutorial.model.DaoSession;
import com.example.tutorial.model.Task;
import com.example.tutorial.model.TaskDao;
import com.example.tutorial.ultils.DateUltil;

/**
 * Thuc hien add task
 * 
 * @author vanch_000
 * 
 */
public class AddTaskActity extends Activity implements OnClickListener {

	// property control
	ImageView imgChooseDueOn;
	ImageView imgChooseTime;
	ImageView imgListTask;
	ImageView imgSave;
	EditText txtTitle;
	EditText txtContent;
	TextView lblNotifyTime;
	TextView lblDueOn;
	Button btnSave;
	Button btnPush;

	public int yearr;
	public int month;
	public int day;
	public int hours;
	public int minutes;

	static final int DATE_DIALOG_ID = 0;
	static final int TIME_DIALOG_ID = 1;

	boolean isEdit = false;
	Task editTask;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_task);

		// find id control
		findIdControl();

		// mac dinh show dialog la ngay hien tai
		Calendar cal = Calendar.getInstance();
		yearr = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		day = cal.get(Calendar.DAY_OF_MONTH);
		hours = cal.get(Calendar.HOUR_OF_DAY);
		minutes = cal.get(Calendar.MINUTE);

		// set onclick
		imgChooseDueOn.setOnClickListener(this);
		imgChooseTime.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		imgSave.setOnClickListener(this);
		imgListTask.setOnClickListener(this);
		btnPush.setOnClickListener(this);
		btnPush.setEnabled(false);

		// get id tu ben List truyen sang de thuc hien edit
		Intent intent = getIntent();
		getIntentEditTask(intent);
	}

	private void getIntentEditTask(Intent intent) {
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				Long taskId = bundle.getLong("TASKID");
				if (taskId != null && taskId > 0) {
					DevOpenHelper helper = new DevOpenHelper(this, "task-db",
							null);
					SQLiteDatabase db = helper.getWritableDatabase();
					DaoMaster daoMaster = new DaoMaster(db);
					DaoSession daoSession = daoMaster.newSession();
					TaskDao taskDao = daoSession.getTaskDao();
					// lay thong tin chi tiet mot task
					Task task = taskDao.load(taskId);
					if (task != null) {
						btnPush.setEnabled(true);
						isEdit = true;
						editTask = task;
						// dialog date picker
						day = task.getNotifyDate().getDate();
						month = task.getNotifyDate().getMonth();
						yearr = task.getNotifyDate().getYear();
						lblDueOn.setText(day + "/" + month + "/" + yearr);
						// dialog time picker
						hours = task.getNotifyDate().getHours();
						minutes = task.getNotifyDate().getMinutes();
						lblNotifyTime.setText(hours + ":" + minutes);
						txtTitle.setText(task.getTitle());
						txtContent.setText(task.getContent());
					}
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * find control
	 */
	private void findIdControl() {
		imgChooseDueOn = (ImageView) findViewById(R.id.imgChooseDueOn);
		imgChooseTime = (ImageView) findViewById(R.id.imgChooseTime);
		imgSave = (ImageView) findViewById(R.id.imgSave);
		imgListTask = (ImageView) findViewById(R.id.imgListTask);
		txtTitle = (EditText) findViewById(R.id.txtTitle);
		txtContent = (EditText) findViewById(R.id.txtContent);
		lblNotifyTime = (TextView) findViewById(R.id.lblNotifyTime);
		lblDueOn = (TextView) findViewById(R.id.lblDueOn);
		btnSave = (Button) findViewById(R.id.btnSave);
		btnPush = (Button) findViewById(R.id.btnPush);
	}

	/**
	 * Event save task
	 * 
	 * @param v
	 */
	private void onSave() {
		try {
			String title = txtTitle.getText().toString();
			String content = txtContent.getText().toString();
			if ("".equals(title) || title.length() == 0 || title == null) {
				txtTitle.setHint("Ban chua nhap title");
			}
			if ("".equals(content) || content.length() == 0 || content == null) {
				txtContent.setHint("Ban chua nhap content");
			}

			addTask(title, content);
		} catch (Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
	}

	private void addTask(String title, String content) {
		// bat dau thuc hien add
		DevOpenHelper helper = new DevOpenHelper(this, "task-db", null);
		SQLiteDatabase db = helper.getWritableDatabase();
		DaoMaster daoMaster = new DaoMaster(db);
		DaoSession daoSession = daoMaster.newSession();
		TaskDao taskDao = daoSession.getTaskDao();

		Task t = new Task();
		t.setTitle(title);
		t.setContent(content);
		t.setUserId(1);
		t.setIsSynchronize(false);
		java.util.Date notifyDate = new java.util.Date(yearr, month, day,
				hours, minutes);
		java.util.Date currentDate = new java.util.Date();
		t.setNotifyDate(notifyDate);
		if (DateUltil.compare2Date(notifyDate, currentDate) == 1 ||
				DateUltil.compare2Date(notifyDate, currentDate) == 0) {
			t.setIsCompleted(false);
		} else if (DateUltil.compare2Date(notifyDate, currentDate) == -1) {
			t.setIsCompleted(true);
		}
		t.setDateCreated(currentDate);
		if (!isEdit) {
			// add
			long id = taskDao.insert(t);
			if (id > 0) {
				Log.d("SUCCESS", "insert thanh cong");
				Toast.makeText(this, "Insert task success.", Toast.LENGTH_LONG)
						.show();
				txtTitle.setText("");
				txtContent.setText("");
			} else if (id <= 0) {
				Log.d("FAIELD", "insert that bai");
				Toast.makeText(this, "Insert task failed.", Toast.LENGTH_LONG)
						.show();
			}
		} else {
			// edit
			if (editTask != null) {
				t.setId(editTask.getId());
				t.setDateCreated(editTask.getDateCreated());
				t.setUserId(editTask.getUserId());
				t.setIsSynchronize(editTask.getIsSynchronize());

				taskDao.update(t);
				Log.d("SUCCESS", "update thanh cong");
				Toast.makeText(this, "Update task success.", Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	/**
	 * Event click image calendar
	 */
	private void changeDueOn() {
		Log.d("", "--changeDueOn--");
		showDialog(DATE_DIALOG_ID);
	}

	/**
	 * Event click image time
	 * 
	 * @param v
	 */
	private void changeTime() {
		Log.d("", "--changeTime--");
		showDialog(TIME_DIALOG_ID);
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// khi dialog dong se call den method nay
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			Log.d("", "--datePickerListener--");
			yearr = year;
			month = monthOfYear + 1;
			day = dayOfMonth;
			// hien thi date len textview
			StringBuilder sb = new StringBuilder();
			sb.append(pad(day));
			sb.append("/");
			sb.append(pad(month));
			sb.append("/");
			sb.append(yearr);
			lblDueOn.setText(sb);
		}
	};

	private TimePickerDialog.OnTimeSetListener timePickerListener = new OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			Log.d("", "--timePickerListener--");

			hours = hourOfDay;
			minutes = minute;

			// hien thi thoi gian len textview
			StringBuilder sb = new StringBuilder();
			sb.append(pad(hours));
			sb.append(":");
			sb.append(pad(minutes));
			lblNotifyTime.setText(sb);
		}
	};

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, datePickerListener, yearr, month,
					day);
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, timePickerListener, hours,
					minutes, true);
		default:
			break;
		}

		return null;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.imgChooseDueOn:
			changeDueOn();
			break;
		case R.id.imgChooseTime:
			changeTime();
			break;
		case R.id.btnSave:
			onSave();
			break;
		case R.id.imgListTask:
			Intent intent1 = new Intent(getApplicationContext(),
					ListTaskActity.class);
			startActivity(intent1);
			break;
		case R.id.imgSave:
			onSave();
			break;
		case R.id.btnPush:
			pushNotifyMessage();
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("deprecation")
	private void pushNotifyMessage() {
		NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		Notification nofity = new Notification(
				android.R.drawable.stat_notify_more, txtTitle.getText()
						.toString(), System.currentTimeMillis());
		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, new Intent(), 0);
		nofity.setLatestEventInfo(getApplicationContext(), txtTitle.getText()
				.toString(), txtContent.getText().toString(), pendingIntent);
		NM.notify(0, nofity);
	}
}
